<?php

ini_set('memory_limit','64GB');

use Swoole\Coroutine;
use Swoole\Coroutine\Http\Client;
use function Swoole\Coroutine\run;

function faker($page = 0)
{
    $client = new Client('openapi.stupideyes.com', 443, true);
    $client->get('/faker?offset=' . $page);
    $client->close();

    return json_decode($client->getBody(), true);
}

run(function () {
    $offset = 1;

    $success = 0;
    for ($i = 1; $i <= 10000; $i++) {
        $faker = faker($offset);
        $offset++;
        go(function () use ($faker, $offset, &$success) {
            $socket = new Swoole\Coroutine\Http\Client('43.248.128.57', 14101);
            $socket->upgrade("/ws?access_token=" . $faker['params']['token']);
            if ($socket->connected) {
                $success += 1;

                while (true) {
                    $socket->recv();
//                    $socket->push('hello');
//                    var_dump($socket->recv());

                    Coroutine::sleep(0.1);
                }
            } else {
                $success -= 1;

                echo 'websocket fail: ' . socket_strerror($socket->errCode) . PHP_EOL;
            }
        });

        Coroutine::sleep(0.1);

        var_dump($success);
    }


});